//在测试时要在编译末尾加[-pthead]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/select.h>
#include <sys/time.h>
#include <pthread.h>
//全局数据类型定义
#define ElemType int
#define ElemTypes char
#define Internet_Protocol ("192.168.20.128")
//函数库
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
//线程A
void* Thread_A(void* arg){
    pthread_mutex_lock(&lock);
    printf("线程A开始运行\n");
    //客户端->广播调度系统
    //创建UDP通信通道socket
    ElemType UDP_socket_FD = socket(AF_INET, SOCK_DGRAM, 0);
    if (UDP_socket_FD == -1){
        printf("通道创建失败， 有错误信息: %s\n", strerror(errno));
        return NULL;
    }
    //地址信息
    struct sockaddr_in dest_addr;
    //初始化
    bzero(&dest_addr, sizeof(dest_addr));
    dest_addr.sin_family = AF_INET;
    ElemTypes buff[1024] = {0};
    //发送信息
    while (1){
        ElemType port;
        printf("1.广播\n2.单聊\n业务选择:");
        scanf("%d", &port);
        printf("\n");
        if (1 == port){
            printf("要发信息：");
            scanf("%s",buff);
            printf("\n");
            //输入目的IP端口
            //网络通信为大端格式
            dest_addr.sin_port = htons(8888);
            //32位整形
            dest_addr.sin_addr.s_addr = inet_addr("230.52.52.52");
            if (sendto(UDP_socket_FD, buff, strlen(buff), 0, (struct sockaddr*)&dest_addr, sizeof(dest_addr)) == -1){
            printf("发送失败， 错误信息: %s\n", strerror(errno));
            break;
            //清空接收到的信息， 避免影响下次接收
            memset(buff, 0, sizeof(buff));
            }
        }else if (2 == port){
            //遍历用户快乐.c为可执行文件user
            system("gcc -o user 用户快乐.c -pthread");
            //调用可执行文件user
            system("./user");
        }else{
            ElemType lobsterarr = port;
            if (0 == lobsterarr){
                //将缓冲区中的杂质装起来
                ElemTypes lobsterarr[1024];
                //进行清空
                scanf("%s", lobsterarr);
            }
            printf("输入错误\n");
            sleep(1);
            system("clear");
        }
        }
    //关闭通信通道socket
    close(UDP_socket_FD);
    pthread_mutex_unlock(&lock);
    return NULL;
}
//线程B
void* Thread_B(void* arg){
    printf("线程C开始运行\n");
    //全境广播系统->客户端
    //创建UDP通信通道socket
    ElemType UDP_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == UDP_socket_fd){
        perror("socket failed\n");
        return NULL;
    }
    //设置发送方IP地址
    struct sockaddr_in send_addr;
    //初始化服务器地址
    bzero(&send_addr, sizeof(send_addr));
    //IPV4协议
    send_addr.sin_family = AF_INET;
    //设置发送方端口号
    send_addr.sin_port = 0;
    //系统检测本地网卡， 自动绑定本地IP
    send_addr.sin_addr.s_addr = inet_addr(Internet_Protocol);
    ElemType ret = bind(UDP_socket_fd, (struct sockaddr*)&send_addr, sizeof(send_addr));
    if (ret < 0){
        perror("bind fail:");
        close(UDP_socket_fd);
        return NULL;
    }else
        printf("连接准备就绪\n");
    //储存信息发送方的IP地址
    struct sockaddr_in src_addr;
    //初始化
    bzero(&src_addr, sizeof(src_addr));
    //地址信息大小
    ElemType len = sizeof(src_addr);
    //信息缓冲区
    ElemTypes buff[1024] = {0};
    ElemType i, j;
    //循环接收客户端发送过来的数据
    while (1){
    ret = recvfrom(UDP_socket_fd, buff, sizeof(buff), 0, (struct sockaddr*)&src_addr, &len);
    if (ret == -1)
        return NULL;
    //打印消息发送方的IP与端口号
    //清屏
    system("clear");
    if (ret != 0){
        printf("===========");
        for (i = 0; i < strlen(buff); i++)
            printf("=");
        printf("\n||广播信息: %s||\n", buff);
        for (i = 0; i < strlen(buff); i++)
            printf("=");
        printf("===========\n");
        printf("1.广播\n2.单聊\n业务选择:\n");
        printf("输入421可回到上一次界面\n");
        printf("退出: exit\n");
    }
    }
    //清空缓冲区
    memset(buff, 0, sizeof(buff));
    //关闭通信通道
    close(UDP_socket_fd);
    return NULL;
}
ElemType main(){
	//创建UDP套接字socket
	ElemType sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd<0)
		perror("socket error");
	//准备广播地址和端口
	struct sockaddr_in servaddr;
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons (10086);
	servaddr.sin_addr.s_addr = inet_addr(Internet_Protocol);
	//设置广播套接字选项 SO_BROADCAST
	ElemType so_broadcast = 1;
	if(setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof(so_broadcast)) < 0){
		perror("setsockopt");
		close(sockfd);
		return -1;
	}
	//使用 sendto 发送广播数据报
	if(sendto(sockfd, "", strlen("已完成通信通道的建立\n"), 0, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
		perror("发送错误原因\n");
	//处理应答
	ElemTypes recvline[256];
	ElemType n = 0;
	struct sockaddr_in tmpAddr;
	bzero(&tmpAddr, sizeof(tmpAddr));
	socklen_t addrLen=sizeof(tmpAddr);
    //清屏
    system("clear");
	while ((n = recvfrom (sockfd, recvline, sizeof(recvline), 0, (struct sockaddr*)&tmpAddr, &addrLen)) > 0){
		recvline[n] = 0 ;
		printf("接收IP=[%s], [%s]\n",inet_ntoa(tmpAddr.sin_addr), recvline);
		bzero(&tmpAddr, sizeof(tmpAddr));
            pthread_t ThreadA, ThreadB;
            pthread_create(&ThreadA, NULL, Thread_A, NULL);
            pthread_create(&ThreadB, NULL, Thread_B, NULL);
            pthread_join(ThreadA, NULL);
            pthread_join(ThreadB, NULL);
            pthread_mutex_destroy(&lock);
	}
	if (n < 0)
		perror("read error" );
	//关闭
	close(sockfd);
	return 0;
}
